package com.gzh.redis_to_mq.redis;

import com.gzh.redis_to_mq.listener.RedisListener;
import io.netty.util.internal.logging.InternalLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Description TODO
 * @Author gzh
 * @Date 2020/10/26 11:20
 */
@Configuration
public class RedisConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class);

    @Autowired
    private RedisListener redisListener;

    /**
     * 配置RedisTemplate，解决乱码问题
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate1(RedisConnectionFactory factory) {

        LOGGER.debug("redis序列化配置开始");

        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();

        template.setConnectionFactory(factory);

        // string序列化方式

        RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();

        // 设置默认序列化方式

        template.setDefaultSerializer(serializer);

        template.setKeySerializer(new StringRedisSerializer());

        template.setHashValueSerializer(serializer);

        LOGGER.debug("redis序列化配置结束");

        return template;

    }


    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();

        container.setConnectionFactory(factory);

        container.addMessageListener(redisListener, new PatternTopic("demo-channel"));

        return container;

    }

}
